<template>
  <view class="cart-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left" @click="onBack">
        <text class="header-back">返回</text>
      </view>
      <view class="header-title">购物车 ({{ groupedCartItems.length }})</view>
      <view class="header-right" @click="onManage">
        <text class="header-manage">管理</text>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-tags">
      <view
          class="filter-tag"
          :class="{ active: currentFilter === 'available' }"
          @click="onFilter('available')"
      >
        可购买
      </view>
      <view
          class="filter-tag"
          :class="{ active: currentFilter === 'discounted' }"
          @click="onFilter('discounted')"
      >
        降价
      </view>
    </view>

    <!-- 购物车商品列表 -->
    <view class="cart-list">
      <!-- 商家分组 -->
      <view
          class="seller-group"
          v-for="(seller, sellerIndex) in groupedCartItems"
          :key="seller.sellerId"
      >
        <view class="seller-header">
          <view class="seller-info">
            <text class="seller-name">{{ seller.sellerName }}</text>
            <text class="seller-chat" @click="onChat(seller.sellerId)">联系卖家</text>
          </view>
          <view class="seller-actions">
            <text
                class="seller-action"
                @click="onSellerAction(sellerIndex, 'selectAll')"
            >
              {{ seller.isAllSelected ? '取消全选' : '全选' }}
            </text>
          </view>
        </view>

        <!-- 商品列表 -->
        <view class="product-list">
          <view
              class="product-item"
              v-for="(item, itemIndex) in seller.items"
              :key="item.id"
          >
            <view class="product-select" @click="onSelect(sellerIndex, itemIndex)">
              <text class="select-icon" :class="{ selected: item.isSelected }">
                {{ item.isSelected ? '✓' : '○' }}
              </text>
            </view>
            <image
                class="product-image"
                :src="item.imageUrl"
                mode="aspectFill"
            ></image>
            <view class="product-info">
              <view class="product-name">{{ item.name }}</view>
              <view class="product-spec">{{ item.spec }}</view>
              <view class="product-tags">
                <text
                    class="product-tag"
                    v-for="(tag, tagIndex) in item.tags"
                    :key="tagIndex"
                >
                  {{ tag }}
                </text>
              </view>
              <view class="product-price">
                <text class="price">¥{{ item.price }}</text>
                <text class="price-desc">{{ item.priceDesc }}</text>
              </view>
              <view class="product-stock" v-if="item.stockInfo">
                <text>{{ item.stockInfo }}</text>
              </view>
            </view>
            <view class="product-quantity">
              <view class="quantity-btn" @click="onDecrease(sellerIndex, itemIndex)">-</view>
              <view class="quantity-value">{{ item.quantity }}</view>
              <view class="quantity-btn" @click="onIncrease(sellerIndex, itemIndex)">+</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="checkout-bar">
      <view class="checkout-select-all" @click="onSelectAll">
        <text class="select-all-icon" :class="{ selected: isAllSelected }">
          {{ isAllSelected ? '✓' : '○' }}
        </text>
        <text class="select-all-text">全选</text>
      </view>
      <view class="checkout-total">
        <text class="total-label">合计:</text>
        <text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
      </view>
      <button
          class="checkout-btn"
          :disabled="selectedCount === 0"
          @click="onCheckout"
      >
        结算 ({{ selectedCount }})
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 模拟购物车数据
const cartItems = ref([
  {
    id: '1',
    sellerId: 'seller1',
    sellerName: '小明的闲置',
    name: '99新 MacBook Pro 13',
    spec: '2020款/16G/512G/银色',
    price: 7999,
    priceDesc: '原价9800，使用3个月',
    tags: ['可小刀', '包邮', '个人闲置'],
    stockInfo: '仅此一件，手慢无',
    imageUrl: 'https://picsum.photos/seed/macbook/200/200',
    quantity: 1,
    isSelected: true
  },
  {
    id: '2',
    sellerId: 'seller2',
    sellerName: '运动达人',
    name: '迪卡侬山地自行车',
    spec: '27.5寸/24速/铝合金车架',
    price: 1299,
    priceDesc: '原价2000，使用1年',
    tags: ['可小刀', '自提优先', '九成新'],
    stockInfo: '同城可自提，包邮加50',
    imageUrl: 'https://picsum.photos/seed/bike/200/200',
    quantity: 1,
    isSelected: false
  },
  {
    id: '3',
    sellerId: 'seller2',
    sellerName: '运动达人',
    name: '全新未拆封瑜伽垫',
    spec: '8mm厚/防滑/环保TPE材质',
    price: 89,
    priceDesc: '原价129，全新未拆封',
    tags: ['包邮', '全新', '可议价'],
    stockInfo: '仅1件，拍下后48小时内发货',
    imageUrl: 'https://picsum.photos/seed/yogamat/200/200',
    quantity: 1,
    isSelected: false
  }
]);

// 当前筛选条件
const currentFilter = ref('all');

// 分组后的购物车数据
const groupedCartItems = computed(() => {
  const groups = {};

  // 按商家分组
  cartItems.value.forEach(item => {
    if (!groups[item.sellerId]) {
      groups[item.sellerId] = {
        sellerId: item.sellerId,
        sellerName: item.sellerName,
        isAllSelected: false,
        items: []
      };
    }
    groups[item.sellerId].items.push(item);
  });

  // 计算每个商家是否全选
  Object.values(groups).forEach(group => {
    group.isAllSelected = group.items.every(item => item.isSelected);
  });

  return Object.values(groups);
});

// 根据筛选条件过滤商品
const filteredCartItems = computed(() => {
  switch (currentFilter.value) {
    case 'available':
      // 这里可以根据实际需求添加更多筛选逻辑
      return cartItems.value;
    case 'discounted':
      // 这里可以实现降价商品的筛选逻辑
      return cartItems.value.filter(item => item.price < (item.price * 1.2)); // 假设比原价低20%算降价
    default:
      return cartItems.value;
  }
});

// 计算总价
const totalPrice = computed(() => {
  return filteredCartItems.value
      .filter(item => item.isSelected)
      .reduce((total, item) => total + item.price * item.quantity, 0);
});

// 计算已选商品数量
const selectedCount = computed(() => {
  return filteredCartItems.value.filter(item => item.isSelected).length;
});

// 计算是否全选
const isAllSelected = computed(() => {
  return filteredCartItems.value.length > 0 &&
      filteredCartItems.value.every(item => item.isSelected);
});

// 返回上一页
const onBack = () => {
  uni.navigateBack();
};

// 管理购物车
const onManage = () => {
  console.log('管理购物车');
};

// 筛选商品
const onFilter = (filterType) => {
  currentFilter.value = filterType;
  console.log('筛选商品:', filterType);
};

// 选择/取消选择商品
const onSelect = (sellerIndex, itemIndex) => {
  const item = groupedCartItems.value[sellerIndex].items[itemIndex];
  item.isSelected = !item.isSelected;

  // 更新商家的全选状态
  groupedCartItems.value[sellerIndex].isAllSelected =
      groupedCartItems.value[sellerIndex].items.every(item => item.isSelected);
};

// 全选/取消全选
const onSelectAll = () => {
  const newState = !isAllSelected.value;
  filteredCartItems.value.forEach(item => {
    item.isSelected = newState;
  });

  // 更新所有商家的全选状态
  groupedCartItems.value.forEach(group => {
    group.isAllSelected = newState;
  });
};

// 增加商品数量
const onIncrease = (sellerIndex, itemIndex) => {
  const item = groupedCartItems.value[sellerIndex].items[itemIndex];
  item.quantity++;
};

// 减少商品数量
const onDecrease = (sellerIndex, itemIndex) => {
  const item = groupedCartItems.value[sellerIndex].items[itemIndex];
  if (item.quantity > 1) {
    item.quantity--;
  }
};

// 商家操作
const onSellerAction = (sellerIndex, actionType) => {
  const group = groupedCartItems.value[sellerIndex];
  if (actionType === 'selectAll') {
    const newState = !group.isAllSelected;
    group.items.forEach(item => {
      item.isSelected = newState;
    });
    group.isAllSelected = newState;
  }
};

// 联系卖家
const onChat = (sellerId) => {
  console.log('联系卖家:', sellerId);
  uni.navigateTo({
    url: `/pages/chat/index?sellerId=${sellerId}`
  });
};

// 结算
const onCheckout = () => {
  if (selectedCount.value === 0) {
    uni.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    });
    return;
  }

  console.log('结算商品:', filteredCartItems.value.filter(item => item.isSelected));
  uni.navigateTo({
    url: '/pages/order/confirm'
  });
};

// 页面加载时获取购物车数据
onMounted(() => {
  console.log('购物车页面加载');
});
</script>

<style scoped lang="scss">
.cart-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
    padding: 0 16px;
    background-color: #ffffff;
    border-bottom: 1px solid #eeeeee;

    .header-left, .header-right {
      display: flex;
      align-items: center;
    }

    .header-back, .header-manage {
      font-size: 16px;
      color: #333333;
    }

    .header-title {
      font-size: 18px;
      font-weight: bold;
      color: #333333;
    }
  }

  .filter-tags {
    display: flex;
    padding: 8px 16px;
    background-color: #ffffff;

    .filter-tag {
      padding: 4px 12px;
      margin-right: 12px;
      border-radius: 16px;
      font-size: 14px;
      color: #666666;
      background-color: #f5f5f5;

      &.active {
        color: #ff4500;
        background-color: #ffebe6;
      }
    }
  }

  .cart-list {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 60px; // 为底部结算栏留出空间
  }

  .seller-group {
    margin-bottom: 16px;
    background-color: #ffffff;

    .seller-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 16px;
      border-bottom: 1px solid #eeeeee;

      .seller-info {
        display: flex;
        align-items: center;

        .seller-name {
          font-size: 14px;
          color: #333333;
          margin-right: 8px;
        }

        .seller-chat {
          font-size: 12px;
          color: #ff4500;
          padding: 2px 6px;
          border: 1px solid #ff4500;
          border-radius: 4px;
        }
      }

      .seller-actions {
        .seller-action {
          font-size: 14px;
          color: #ff4500;
        }
      }
    }

    .product-list {
      .product-item {
        display: flex;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #eeeeee;

        .product-select {
          width: 40px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;

          .select-icon {
            font-size: 20px;
            color: #cccccc;

            &.selected {
              color: #ff4500;
            }
          }
        }

        .product-image {
          width: 80px;
          height: 80px;
          margin-right: 12px;
          border-radius: 4px;
        }

        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .product-name {
            font-size: 14px;
            color: #333333;
            margin-bottom: 4px;
          }

          .product-spec {
            font-size: 12px;
            color: #999999;
            margin-bottom: 4px;
          }

          .product-tags {
            display: flex;
            margin-bottom: 4px;

            .product-tag {
              font-size: 10px;
              color: #ff4500;
              background-color: #ffebe6;
              padding: 2px 4px;
              border-radius: 4px;
              margin-right: 4px;
            }
          }

          .product-price {
            display: flex;
            align-items: baseline;

            .price {
              font-size: 14px;
              font-weight: bold;
              color: #ff4500;
              margin-right: 4px;
            }

            .price-desc {
              font-size: 12px;
              color: #999999;
            }
          }

          .product-stock {
            font-size: 12px;
            color: #999999;
          }
        }

        .product-quantity {
          display: flex;
          align-items: center;

          .quantity-btn {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #eeeeee;
            font-size: 16px;
            color: #333333;
          }

          .quantity-value {
            width: 32px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-top: 1px solid #eeeeee;
            border-bottom: 1px solid #eeeeee;
            font-size: 14px;
            color: #333333;
          }
        }
      }
    }
  }

  .checkout-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    background-color: #ffffff;
    border-top: 1px solid #eeeeee;
    padding: 0 16px;

    .checkout-select-all {
      display: flex;
      align-items: center;

      .select-all-icon {
        font-size: 20px;
        color: #cccccc;
        margin-right: 4px;

        &.selected {
          color: #ff4500;
        }
      }

      .select-all-text {
        font-size: 14px;
        color: #333333;
      }
    }

    .checkout-total {
      display: flex;
      align-items: baseline;
      margin-right: 16px;

      .total-label {
        font-size: 14px;
        color: #333333;
        margin-right: 4px;
      }

      .total-price {
        font-size: 16px;
        font-weight: bold;
        color: #ff4500;
      }
    }

    .checkout-btn {
      height: 36px;
      line-height: 36px;
      padding: 0 24px;
      background-color: #ff4500;
      color: #ffffff;
      border-radius: 18px;
      font-size: 14px;
      border: none;
    }
  }
}
</style>
